package pers.lance.xml.parse;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;

public class BookHandler extends DefaultHandler {

    String tag = null;
    List<Book> books = null;
    Book book;

    @Override
    public void startDocument() throws SAXException {

    }

    @Override
    public void endDocument() throws SAXException {
    }

    @Override
    public void startElement(String uri, String localName,
                             String qName, Attributes attributes)
            throws SAXException {
        tag = qName;
        if (qName.equals("books")) {
            books = new ArrayList<Book>();
        }
        if (qName.equals("book")) {
            book = new Book();
            book.setId(Integer.parseInt(attributes.getValue("id")));
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (qName.equals("book")) {
            books.add(book);
        }
        tag = null;
    }

    @Override
    public void characters(char ch[], int start, int length)
            throws SAXException {
        String value = new String(ch, start, length).trim();
        if (tag.equals("name") && !value.equals("")) {
            book.setBookname(value);
        }
        if (tag.equals("price") && !value.equals("")) {
            book.setBookprice(Double.parseDouble(value));
        }

    }

    public List<Book> getBooks() {
        return books;
    }
}
